package com.hkbigdata.StreamCode;

import com.hkbigdata.entry.UserBehavior;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author liuanbo
 * @creat 2023-04-26-19:29
 * @see 2194550857@qq.com
 */
public class Flink02_PageView_Process {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMap = env.readTextFile("input/UserBehavior.csv")
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] split = value.split(",");

                        //1.转换为javabean
                        UserBehavior userBehavior = new UserBehavior(
                                Long.parseLong(split[0]),
                                Long.parseLong(split[1]),
                                Integer.parseInt(split[2]),
                                split[3],
                                Long.parseLong(split[4])
                        );

                        //2.只要pv数据
                        if ("pv".equals(userBehavior.getBehavior())) {
                            out.collect(new Tuple2<>("pv", 1));
                        }
                    }
                });

        KeyedStream<Tuple2<String, Integer>, String> keyedStream = flatMap.keyBy(data -> data.f0);

        keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Integer>() {
            int count = 0;

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Integer> out) throws Exception {
                count++;
                out.collect(count);
            }
        }).print();


        env.execute();
    }
}
